package com.jiefutong.zyt.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.jiefutong.zyt.R;
import com.squareup.picasso.Picasso;

import java.util.List;


/**
 * 图片自动滚动适配器
 */
public class AutoScrollImgPagerAdapter extends RecyclingPagerAdapter {
    private static final Gson gson = new Gson();
    private Context context;

    /**
     * 图片列表
     */
    private List<String> imageList;

    /**
     * 图片列表的大小
     */
    private int size;

    /**
     * 是否循环播放
     */
    private boolean isInfiniteLoop;

    /**
     * 图片配置选项
     */

    public AutoScrollImgPagerAdapter(Context context, List<String> imageList) {
        this.context = context;
        this.imageList = imageList;
        this.size = imageList.size();
        isInfiniteLoop = false;
    }

    @Override
    public int getCount() {
        return isInfiniteLoop ? Integer.MAX_VALUE : size;
    }

    public int getPosition(int position) {
        return isInfiniteLoop ? position % size : position;
    }

    @Override
    public View getView(final int position, View view, final ViewGroup container) {
        ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = LayoutInflater.from(context).
                    inflate(R.layout.layout_auto_scroll_img, container, false);
            holder.imageView = (ImageView) view.findViewById(R.id.imageView);
           // holder.progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();

        }
        final String imgUrl = imageList.get(getPosition(position));
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
       /* if(imgUrl!=-1){
            holder.imageView.setImageResource(imgUrl);
        }*/
        if(!TextUtils.isEmpty(imgUrl)){
            Picasso.with(context).load(imgUrl).into( holder.imageView);
        }
        //holder.imageView.setTag(holder.progressBar);
        return view;
    }

    private static class ViewHolder {
        ImageView imageView;
        //ProgressBar progressBar;
    }

    /**
     * 是否循环播放图片
     *
     * @return true/false
     */
    public boolean isInfiniteLoop() {
        return isInfiniteLoop;
    }

    /**
     * 设置是否循环播放图片
     *
     * @param isInfiniteLoop true/false
     * @return AutoScrollImgPagerAdapter实例
     */
    public AutoScrollImgPagerAdapter setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
        return this;
    }
}
